package com.xzx.flink.streamapi.sink;

import com.mysql.jdbc.Driver;
import com.xzx.flink.bean.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @author xinzhixuan
 * @version 1.0
 * @date 2021-08-29 10:41 下午
 */
public class Sink_05_JDBC {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> streamSource = env.readTextFile("/Users/xinzhixuan/work/git/flink-study-java/src/main/resources/sensor.txt");
        SingleOutputStreamOperator<SensorReading> map = streamSource.map(new MapFunction<String, SensorReading>() {
            @Override
            public SensorReading map(String value) throws Exception {
                String[] split = value.split(" ");
                return new SensorReading(split[0], Long.parseLong(split[1]), Double.parseDouble(split[2]));
            }
        });
        map.print();

        map.addSink(JdbcSink.sink("insert into sensor (id, ts, temperature) values (?,?,?)",
                (JdbcStatementBuilder<SensorReading>) (preparedStatement, sensorReading) -> {
                    preparedStatement.setString(1, sensorReading.getId());
                    preparedStatement.setLong(2, sensorReading.getTimestamp());
                    preparedStatement.setDouble(3, sensorReading.getTemperature());
                },
                new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                        .withUrl("jdbc:mysql://localhost:3306/flink")
                        .withUsername("root")
                        .withPassword("12345678")
                        .withDriverName(Driver.class.getName())
                        .build()));

        env.execute(Sink_05_JDBC.class.getName());
    }
}
